<template>
  <div>
    <h1 style="text-align: center">Increment Code Coverage</h1>
    <hr>
    <!-- 筛选模块 -->
    <div class="filterStyle">
      <!-- 作者 -->
      <el-select v-model="currentContributor" style="margin-left: 20px" placeholder="请选择" @change="selectedContributorHandle">
        <el-option v-for="item in contributorArray" :key="item" :label="item" :value="item" />
      </el-select>
      <!-- 需求 -->
      <el-select v-model="currentTask" style="margin-left: 20px" placeholder="请选择" @change="selectedTaskHandle">
        <el-option v-for="item in taskArray" :key="item" :label="item" :value="item" />
      </el-select>
    </div>
    <!-- 总体进度 -->
    <div class="horizonCenterStyle" style="margin-top: 30px;">
      <el-progress type="dashboard" :percentage="currentTotalPercentage" :color="progressColors" />
    </div>
    <div class="horizonCenterStyle" style="margin-top: 15px;margin-bottom: 15px;">
      <el-tag type="success" style="" color="#ffffff">Executed Line Count: {{ executedLine }}</el-tag>
      <el-tag type="success" style="margin-left: 20px;" color="#ffffff">Total Coverage：{{ currentTotalPercentage }}%</el-tag>
      <el-tag type="success" style="margin-left: 20px;" color="#ffffff">Total Line Count: {{ totalLine }}</el-tag>
    </div>
    <!-- 列表数据 -->
    <el-table class="tableListStyle" :data="tableData" :cell-style="changeLineStyle" :height="tableHeight" stripe border @cell-click="cellClick">
      <el-table-column sortable prop="date" label="Date" width="160px" />
      <el-table-column prop="commit" label="Commit Description" />
      <el-table-column prop="incrementalCodeLines" label="Incremental Code Lines" width="180px" />
      <el-table-column prop="executedCodeLines" label="Executed Code Lines" width="180px" />
      <el-table-column prop="coverage" label="Coverage" width="100px" />
    </el-table>
  </div>
</template>

<script>

import { getCommitList } from '@/api/commitList'

export default {
  components: {},
  data() {
    return {
      tableData: [],
      tableHeight: 500,
      allDataArray: [],
      // 作者数组
      contributorArray: [],
      // 当前选中的作者
      currentContributor: 'wangtao_03',
      // 需求数组
      taskArray: ['v1020', 'v1019', 'v1018', 'v1017', 'v1016', 'v1015'],
      // 当前的需求
      currentTask: 'v1019',
      // 总的新增行数
      totalLine: 0,
      // 总的已经执行的新增行数
      executedLine: 0,
      // 总的进度
      currentTotalPercentage: 0,
      // 每个进度对应的颜色
      progressColors: [
        { color: '#FF0000', percentage: 30 },
        { color: '#FFFF00', percentage: 60 },
        { color: '#008000', percentage: 100 }
      ]
    }
  },
  created() {
  },
  mounted() {
    this.onWindowResize()
    this.fetchData()
    this.getTableHeight()
  },
  destroyed() {},
  methods: {
    // 获取table的高度
    getTableHeight() {
      this.$nextTick(function() {
        const marginTop = 352
        const marginBottom = 20
        var tableHeight = window.innerHeight - marginBottom - marginTop
        if (tableHeight <= 500) {
          tableHeight = 500
        }
        this.tableHeight = tableHeight
      })
    },
    // 监听window尺寸变化
    onWindowResize() {
      window.onresize = () => {
        if (this.resizeFlag) {
          clearTimeout(this.resizeFlag)
        }
        this.resizeFlag = setTimeout(() => {
          this.getTableHeight()
          this.resizeFlag = null
        }, 100)
      }
    },
    // 请求接口数据
    fetchData() {
      this.listLoading = true
      getCommitList().then(response => {
        console.log('@wangtao', response)
        this.allDataArray = response.data
        this.listLoading = false
        this.handleData()
      })
    },
    // 处理接口数据
    handleData() {
      // 处理开发人员
      this.developerDataHandle()
      // 根据开发人员筛选提交记录
      this.filterCommitWithDeveloper()
      // 计算整体覆盖率
      // this.calculateTotalPercentage()
    },
    // 数组去重
    uniqueArray(arr) {
      return Array.from(new Set(arr))
    },
    // 开发人员的数据处理
    developerDataHandle() {
      var tempContributorData = []
      for (let i = 0; i < this.allDataArray.length; i++) {
        const commit = this.allDataArray[i]
        tempContributorData.push(commit._CommitInfo__author)
      }
      this.contributorArray = this.uniqueArray(tempContributorData)
    },
    // 计算整体的覆盖率
    calculateTotalPercentage() {
      var totalLine = 0
      var executedLine = 0
      for (let i = 0; i < this.allDataArray.length; i++) {
        const commitData = this.allDataArray[i]
        const lineMap = commitData._CommitInfo__realLinesExeNum
        for (const fileName in lineMap) {
          const allLineArray = lineMap[fileName]
          totalLine = totalLine + allLineArray.length
          for (let j = 0; j < allLineArray.length; j++) {
            const lineArray = allLineArray[j]
            if (lineArray.length === 2) {
              const executedCount = lineArray[1]
              if (executedCount > 0) {
                executedLine = executedLine + 1
              }
            }
          }
        }
      }
      if (totalLine <= 0) {
        this.currentTotalPercentage = parseFloat(parseFloat(0).toFixed(2))
      } else {
        this.currentTotalPercentage = parseFloat(parseFloat(executedLine / totalLine * 100).toFixed(2))
      }
      this.totalLine = totalLine
      this.executedLine = executedLine
    },
    // 根据开发人员筛选提交记录
    filterCommitWithDeveloper() {
      var commitArray = []
      var totalLine = 0
      var executedLine = 0
      for (let i = 0; i < this.allDataArray.length; i++) {
        const commitData = this.allDataArray[i]
        const author = commitData._CommitInfo__author
        const lineMap = commitData._CommitInfo__realLinesExeNum
        if (author === this.currentContributor) {
          var commitLine = 0
          var executedCommitLine = 0
          for (const fileName in lineMap) {
            const allLineArray = lineMap[fileName]
            commitLine = commitLine + allLineArray.length
            for (let j = 0; j < allLineArray.length; j++) {
              const lineArray = allLineArray[j]
              if (lineArray.length === 2) {
                const executedCount = lineArray[1]
                if (executedCount > 0) {
                  executedCommitLine = executedCommitLine + 1
                }
              }
            }
          }
          var commitCoverage = parseFloat(0).toFixed(2)
          if (commitLine > 0) {
            commitCoverage = parseFloat(executedCommitLine / commitLine * 100).toFixed(2)
          }
          commitArray.push({
            'date': this.formateTimeStamp(commitData._CommitInfo__timestamp),
            'commit': commitData._CommitInfo__message,
            'incrementalCodeLines': commitLine,
            'executedCodeLines': executedCommitLine,
            'coverage': commitCoverage + ' %',
            'commitId': commitData._CommitInfo__commitId
          })
          totalLine = totalLine + commitLine
          executedLine = executedLine + executedCommitLine
        }
      }
      if (totalLine > 0) {
        this.currentTotalPercentage = parseFloat(parseFloat(executedLine / totalLine * 100).toFixed(2))
      } else {
        this.currentTotalPercentage = parseFloat(parseFloat(0).toFixed(2))
      }
      this.totalLine = totalLine
      this.executedLine = executedLine
      this.tableData = commitArray
    },
    // 切换作者的回调
    selectedContributorHandle(value) {
      this.currentContributor = value
      this.filterCommitWithDeveloper()
    },
    // 切换需求的回调
    selectedTaskHandle(value) {
      this.currentTask = value
    },
    // 点击table某个cell的事件处理
    cellClick(row, column, cell, event) {
      const clickCommitId = row.commitId
      var clickCommitData = {}
      for (let i = 0; i < this.allDataArray.length; i++) {
        const commitData = this.allDataArray[i]
        const tempCommitId = commitData._CommitInfo__commitId
        if (clickCommitId === tempCommitId) {
          clickCommitData = commitData
          break
        }
      }
      if (column.label === 'Commit Description') {
        this.$router.push({
          name: 'commitDetail',
          params: {
            commit: clickCommitData
          }
        })
      }
    },
    // 修改某一列的样式
    changeLineStyle(row, column, rowIndex, columnIndex) {
      if (row.column.label === 'Commit Description') {
        return 'color:#4169E1'
      } else {
        return 'color: black'
      }
    },
    // 时间戳转日期
    formateTimeStamp(time) {
      var date = new Date(time * 1000)
      var year = date.getFullYear()
      var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      var hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      var minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      var second = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
    }
  }
}
</script>

<style lang="scss">

.filterStyle {
  margin-top: 20px;
  text-align: center;
}

.horizonCenterStyle {
  display: flex;
  justify-content: center;
  align-items: center;
}

.tableListStyle {
  width: 70%;
  margin: auto;
}

</style>
